<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Agent_model extends MY_Model {

	var $table = 'agent';
	
	//构造函数
	public function __construct() {
		//调用父类构造函数，必不可少
		parent::__construct();
	}

	/**
	 * 取得所有代理商
	 * 
	 * @param array $config
	 * @param array $like
	 * @return array
	 */
	public function getAgentAll($config = array(), $like = array()) {
		$data = $config;
		$config['field'] = 'd.id';
		$config['select'] = 'd.*,concat(a1.description, \' \', ae1.address) warehouse,i.realname,i.autodyne_id,i.front_id,i.reverse_id,group_concat(concat(a.description,\' \',ae.address) SEPARATOR \'<br/></br/>\') as multiAddress';
		$config['join'] = array(
			array('areas_enabled ae1', 'd.address_id=ae1.id', 'left'),
			array('areas a1', 'ae1.district_id=a1.id', 'left'),
			array('identification i', 'd.id=i.agent_id', 'left'),
			array('agent_assignment da', 'd.id=da.agent_id', 'left'),
			array('areas_enabled ae', 'da.address_id=ae.id', 'left'),
			array('areas a', 'ae.district_id=a.id', 'left')
		);
		$config['group_by'] = 'd.id';
		$data['totalCount'] = $this->get_search_num(NULL, $like, $config, ' d');
		if($config['offset'] >= $data['totalCount']) {
			$data['offset'] = $config['offset'] = 0;
			$data['pageNum'] = $config['pageNum'] = 1;
 		}
		$res = $this->search(NULL, $config, $like, false, ' d');
		$data['data'] = array();
		$ids = array();
		
		if(!empty($res)) {
			foreach ($res as $v) {
				$data['data'][$v['id']] = $v;
				$ids[] = $v['autodyne_id'];
				$ids[] = $v['front_id'];
				$ids[] = $v['reverse_id'];
			}
			$query = $this->db->select('id,source_id,img')->from('album')->where_in('id', $ids)->get();
			$rows = $query->result_array();
			foreach ($rows as $v) {
				switch($v['id']) {
					case $data['data'][$v['source_id']]['autodyne_id']:
						$data['data'][$v['source_id']]['autodyne'] = $v['img'];
						break;
					case $data['data'][$v['source_id']]['front_id']:
						$data['data'][$v['source_id']]['front'] = $v['img'];
						break;
					case $data['data'][$v['source_id']]['reverse_id']:
						$data['data'][$v['source_id']]['reverse'] = $v['img'];
						break;
					default:break;
				}
			}
		}
		return $data;
		
	}

	/**
	 * 删除供货商
	 *
	 * @param string $ids 多个用逗号隔开
	 * @return integer
	 */
	public function deleteAgent($ids) {
		$idsArr = explode(',', $ids);
		return $this->delete(array('id'=>$idsArr));
	}
	
	/**
	 * 增加供货商
	 *
	 * @param array $data
	 * @return integer
	 */
	public function addAgent($data, $data2, $data3) {
		try {
			$this->db->trans_begin();
			$this->db->insert($this->table, $data);
			$id = $this->db->insert_id();
			$data2['agent_id'] = $id;
			if($data['role'] === REST_Controller::ROLE_DILIVERIER) {				
				$this->db->insert('agent_assignment', $data2);
			} else {
				$rows = $this->db->select('address_id')->from('branch_assignment')->where('warehouse_address_id', $data2['address_id'])->get()->result_array();
				if(empty($rows)) {
					throw new Exception('10059');
				}
				$tmp = array();
				foreach ($rows as $v) {
					$data2['address_id'] = $v['address_id'];
					$tmp[] = $data2;
				}
				$this->db->insert_batch('agent_assignment', $tmp);
			}
			$data3['agent_id'] = $id;
			$this->db->insert('identification',$data3);
			$source_ids = array(
				$data3['autodyne_id'],
				$data3['front_id'],
				$data3['reverse_id']
			);
			$this->db->where_in('id', $source_ids);
			$this->db->update('album', array('source_id'=>$id));
			$this->db->trans_complete();
			return true;
		} catch (Exception $e) {
			$this->db->trans_rollBack();
			return intval($e->getMessage());
		}
	}

	
	/**
	 * 更新一条供货商信息
	 *
	 * @param array $data
	 * @param integer $id
	 * @return integer
	 */
	public function updateAgent($data, $id) {
		return $this->update($data, array('id'=>$id));
	}
	
	
	/**
	 * 查找详细信息
	 *
	 * @param integer $id
	 * @return array
	 */
	public function findAgent($id) {
		$sql="select u.*,a.id as aid,a.agent_id as agid,a.status as astatus,e.address,s.description from ck_user u left join ck_agent_assignment a on u.id=a.agent_id left join ck_areas_enabled e on a.address_id=e.id left join ck_areas s on s.id=e.district_id where u.role='1' and a.id={$id}";
		$query = $this->db->select()
				->from($this->table . ' a')
				->join('identification i', 'a.id=i.agent_id', 'left')
				->join('album al', 'i.autodyne_id=al.id', 'left')
				->join('album al1', 'i.front_id=al1.id', 'left')
				->join('album al2', 'i.reverse_id=al2.id', 'left')
				->get();
		$rows = $query->result_array();
		$config['agent']=$query->row_array();
		return $config;
	}
	

}
